package idv.nightpig.lab02.dao.impl;

import idv.nightpig.lab02.dao.GenericDao;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Example;
import org.springframework.beans.factory.annotation.Autowired;

public abstract class GenericDaoHibernateImpl<T, ID extends Serializable> implements GenericDao<T, ID> {

    private Class<T> persistentClass;

    @Autowired
    private SessionFactory sessionFactory;

    @SuppressWarnings("unchecked")
    public GenericDaoHibernateImpl() {
        persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    public List<T> findAll() {
        return findByCriteria();
    }

    @SuppressWarnings("unchecked")
    protected List<T> findByCriteria(Criterion... criterion) {
        Criteria crit = getSession().createCriteria(persistentClass);
        for (Criterion c : criterion) {
            crit.add(c);
        }
        return crit.list();
    }

    public List<T> findByExample(T entity) {
        return findByCriteria(Example.create(entity));
    }

    @SuppressWarnings("unchecked")
    public T findById(ID id) {
        return (T) getSession().get(persistentClass, id);
    }

    public Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    public void persist(T entity) {
        getSession().saveOrUpdate(entity);
    }

    public void remove(T entity) {
        getSession().delete(entity);
    }

}
